﻿using Microsoft.OpenApi.Models;
using SimpleTicketBooking.Utils.Filters;

namespace SimpleTicketBooking.Utils.Ext
{
    /// <summary>
    /// Swagger setting extention
    /// </summary>
    public static class CustomSwaggerExt
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="services"></param>
        public static void AddSwaggerExt(this IServiceCollection services)
        {
            services.AddSwaggerGen(options =>
            {
                options.AddSecurityDefinition("requiredToken", new OpenApiSecurityScheme()
                {
                    In = ParameterLocation.Header,
                    Name = "Authorization",
                    Description = "JWT authorization, input Bearer {token}",
                    Type = SecuritySchemeType.ApiKey
                });

                options.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                     { new OpenApiSecurityScheme
                     {
                          Reference = new OpenApiReference()
                          {
                              Id = "requiredToken",
                              Type = ReferenceType.SecurityScheme
                          }
                     }, Array.Empty<string>() }
                 });

                // 3. set Swagger api default parameters value
                options.SchemaFilter<DefaultValueSchemaFilter>();

                #region 4. load comment on method in Controller
                var file = Path.Combine(AppContext.BaseDirectory, "SimpleTicketBooking.xml");
                options.IncludeXmlComments(file, true);
                options.OrderActionsBy(o => o.RelativePath);
                #endregion

                #region 5. set swager versions
                foreach (var versionNo in typeof(ApiVersions).GetEnumNames().ToList())
                {
                    options.SwaggerDoc(versionNo, new OpenApiInfo()
                    {
                        Title = $"Ticket Booking",
                        Version = versionNo,
                        Description = $"Ticket booking api: {versionNo}"
                    });
                }
                #endregion
            });
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="app"></param>
        public static void UseSwaggerExt(this WebApplication app)
        {
            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                #region 5. set swager versions
                foreach (string version in typeof(ApiVersions).GetEnumNames())
                {
                    c.SwaggerEndpoint($"/swagger/{version}/swagger.json", $"Ticket Booking API: {version}");
                }
                #endregion
            });
        }
    }
}
